package fi.foyt.cs.oauth;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.routing.Filter;

import fi.foyt.cs.Settings;
import fi.foyt.cs.controller.UserController;
import fi.foyt.cs.persistence.domainmodel.user.UserIdentifier;

public class UserCreateFilter extends Filter {

  public UserCreateFilter(Context context) {
    super(context);
  }
  
  @Override
  protected void afterHandle(Request request, Response response) {
    super.afterHandle(request, response);

    Representation r = response.getEntity();
    if (r != null && (r instanceof JsonRepresentation)) {
      JsonRepresentation jr = (JsonRepresentation) r;
      try {
        JSONObject o = jr.getJsonObject();
        if (o != null && o.has("id")) {
          String identifier = o.getString("id");
          String email = o.getString("email");
          String firstName = o.optString("firstname");
          String lastName = o.optString("lastname");
          String fullName = o.optString("fullname");
          
          if (!StringUtils.isBlank(fullName) && (StringUtils.isBlank(firstName) && StringUtils.isBlank(lastName))) {
            String[] names = fullName.split(" ");
            firstName = names[0];
            lastName = names[names.length - 1];
          }
          
          UserController userController = new UserController();
          
          UserIdentifier userIdentifier = userController.findUserIdentifierByIdentifier(identifier);
          if (userIdentifier == null) {
            fi.foyt.cs.persistence.domainmodel.user.User user = userController.findUserByEmail(email);
            if (user == null) {
              user = userController.createUser(firstName, lastName, email, Settings.getDefaultLocale(), false);
            }

            userController.createUserIdentifier(user, identifier);
          }
        }
      } catch (JSONException ignore) {
      }
    }
  }

}
